<script lang="ts" setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";
import { GetRtMinData } from "@/assets/api/rtdatasubscriberservice_0_0_1"; // 导入现有接口

// 图表实例
let timeChart: echarts.ECharts;
let klineChart: echarts.ECharts;
let volumeChart: echarts.ECharts;
let avgPriceChart: echarts.ECharts;

// 图表数据存储
const chartData = ref<Array<{ datetime: number; open: number; high: number; low: number; close: number; volume: number; average: number }>>([]);

// 定时拉取数据
const fetchData = async () => {
  try {
    const response = await GetRtMinData({
      market: 1, // 替换为实际市场标识
      code: "000001", // 替换为实际代码
      filled_up: true,
      fq: 0,
      fre_num: 1, // 1 分钟 K 线
    });

    if (response && response.datas) {
      chartData.value = response.datas;
      updateAllCharts(chartData.value);
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

// 更新图表数据
const updateAllCharts = (data: Array<{ datetime: number; open: number; high: number; low: number; close: number; volume: number; average: number }>) => {
  const timestamps = data.map((item) =>
    new Date(item.datetime.toString().slice(0, 8) + "T" + item.datetime.toString().slice(8, 12)).toLocaleTimeString()
  );

  // K 线图数据
  const klineData = data.map((item) => [item.open, item.high, item.low, item.close]);

  // 成交量数据
  const volumeData = data.map((item) => item.volume);

  // 均价数据
  const avgPriceData = data.map((item) => item.average);

  // 更新分时图（使用均价）
  timeChart.setOption({
    xAxis: { data: timestamps },
    series: [{ data: avgPriceData }],
  });

  // 更新成交量图
  volumeChart.setOption({
    xAxis: { data: timestamps },
    series: [{ data: volumeData }],
  });

  // 更新均价图
  avgPriceChart.setOption({
    xAxis: { data: timestamps },
    series: [{ data: avgPriceData }],
  });

  // 更新 K 线图
  klineChart.setOption({
    xAxis: { data: timestamps },
    series: [{ data: klineData }],
  });
};

// 初始化图表
const initCharts = () => {
  timeChart = echarts.init(document.getElementById("time-chart") as HTMLElement);
  klineChart = echarts.init(document.getElementById("kline-chart") as HTMLElement);
  volumeChart = echarts.init(document.getElementById("volume-chart") as HTMLElement);
  avgPriceChart = echarts.init(document.getElementById("avg-price-chart") as HTMLElement);

  // 基础图表配置
  const baseOption = {
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: [],
    },
    yAxis: {
      type: "value",
    },
    series: [],
  };

  // 设置初始空数据
  timeChart.setOption({ ...baseOption, series: [{ type: "line", smooth: true, lineStyle: { color: "green" } }] });
  volumeChart.setOption({ ...baseOption, series: [{ type: "bar", itemStyle: { color: "#1e90ff" } }] });
  avgPriceChart.setOption({ ...baseOption, series: [{ type: "line", smooth: true, lineStyle: { color: "orange" } }] });
  klineChart.setOption({
    ...baseOption,
    series: [{ type: "candlestick", itemStyle: { color: "#00da3c", borderColor: "#00da3c" } }],
  });
};

// 页面加载时初始化图表并拉取数据
onMounted(() => {
  initCharts();
  fetchData(); // 首次拉取数据
  setInterval(fetchData, 60000); // 每分钟拉取一次数据
});
</script>

<template>
  <div class="new-page">
    <el-button @click="() => window.history.back()">返回</el-button>

    <div class="chart-container-wrapper">
      <div id="time-chart" class="chart-container"></div>
      <div id="volume-chart" class="chart-container"></div>
      <div id="kline-chart" class="chart-container"></div>
      <div id="avg-price-chart" class="chart-container"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.new-page {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;

  .chart-container-wrapper {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 20px;
    height: 100%;
  }

  .chart-container {
    width: 100%;
    height: 100%;
  }
}
</style>
